import React, { useState, useEffect } from 'react';

const RoomList = ({ webRTCService, onRoomSelected }) => {
  const [rooms, setRooms] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!webRTCService) return;

    // 设置房间列表更新监听器
    webRTCService.on('roomList', (roomList) => {
      setRooms(roomList);
      setLoading(false);
    });

    // 请求房间列表
    webRTCService.getRoomList();

    // 每10秒刷新一次房间列表
    const intervalId = setInterval(() => {
      webRTCService.getRoomList();
    }, 10000);

    return () => {
      clearInterval(intervalId);
    };
  }, [webRTCService]);

  const handleJoinRoom = (roomId) => {
    if (onRoomSelected) {
      onRoomSelected(roomId);
    }
  };

  if (loading) {
    return (
      <div className="room-list-container">
        <h2>可用房间</h2>
        <p>加载中...</p>
      </div>
    );
  }

  return (
    <div className="room-list-container">
      <h2>可用房间</h2>
      {rooms.length === 0 ? (
        <p>暂无可用房间</p>
      ) : (
        <ul className="room-list">
          {rooms.map((room) => (
            <li key={room.roomId} className="room-item">
              <div className="room-info">
                <h3>{room.roomName}</h3>
                <div className="room-details">
                  <span>用户数: {room.userCount}</span>
                  {room.hasSharing && (
                    <span className="sharing-badge">正在共享</span>
                  )}
                </div>
              </div>
              <button
                className="btn secondary join-btn"
                onClick={() => handleJoinRoom(room.roomId)}
              >
                加入
              </button>
            </li>
          ))}
        </ul>
      )}
      <button
        className="btn primary refresh-btn"
        onClick={() => webRTCService.getRoomList()}
      >
        刷新列表
      </button>
    </div>
  );
};

export default RoomList; 